fs = require 'fs'
url = require 'url'
path = require 'path'
less = require 'less'

LessPluginAutoPrefix = require('less-plugin-autoprefix')
autoprefix = new LessPluginAutoPrefix({browsers: [
  "ie >= 8"
  "ie_mob >= 10"
  "ff >= 26"
  "chrome >= 30"
  "safari >= 6"
  "opera >= 23"
  "ios >= 5"
  "android >= 2.3"
  "bb >= 10"
]})

module.exports = (root = "#{__dirname}/less", options = {}) ->

  return (req, res, next) ->

    return next() unless req.method is 'GET' or req.method is 'HEAD'

    pathname = url.parse(req.url).pathname

    return next() unless path.extname(pathname) is '.css'

    src = path.join(root, path.dirname(pathname), path.basename(pathname, '.css') + '.less')

    fs.readFile src, (err, data) ->

      next(err) if err

      opts =
        paths: [
          path.join(root, path.dirname(pathname))
        ]
        filename: path.basename(src)
        plugins: [autoprefix]
      opts.compress = !!options.compress

      less.render new String(data), opts, (err, output) ->

        if err
          less.writeError(err) if options.debug
          res.send(500)
        else
          res.set('Content-Type', 'text/css').send(output.css)
